<template>
	<view class="address-page">
		<!-- 地址列表 -->
		<scroll-view class="address-list" scroll-y>
			<!-- 默认地址置顶 -->
			<view v-for="address in sortedAddresses" :key="address.id" class="address-item">
				<view class="address-header">
					<text class="receive-name">{{ address.receiveName }}</text>
					<text class="default-tag" v-if="address.status === 1">默认</text>
					<view class="actions">
						<text class="edit-btn" @click="handleEdit(address)">编辑</text>
						<text class="delete-btn" @click="handleDelete(address)">删除</text>
					</view>
				</view>
				<text class="receive-phone">{{ address.receivePhone }}</text>
				<text class="address-text">{{ address.address }}</text>
				<view class="address-footer">
					<button v-if="address.status !== 1" class="set-default-btn" @click="setAsDefault(address.id)">
						设为默认
					</button>
				</view>
			</view>
			<!-- 空状态 -->
			<view class="empty-tip" v-if="addressList.length === 0">
				<text>暂无收货地址</text>
			</view>
		</scroll-view>

		<view class="add-btn-container">
			<button class="add-btn" @click="showAddForm">新增收货地址</button>
		</view>
		<view v-if="showPopup" class="popup-mask" @click="closePopup">
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<text class="popup-title">{{ isEditing ? '编辑地址' : '新增地址' }}</text>
					<text class="close-btn" @click="closePopup">×</text>
				</view>

				<view class="form-container">
					<view class="form-item">
						<text class="label">收货人</text>
						<input type="text" class="input" v-model="formData.receiveName"
							 placeholder="请输入收货人姓名" />
					</view>

					<view class="form-item">
						<text class="label">手机号码</text>
						<!-- <input class="input"  v-model="formData.receivePhone"
							 placeholder="请输入收货人手机号码" /> -->
							 <input class="input"  v-model="formData.receivePhone"
							 	 placeholder="请输入收货人手机号码" />
					</view>

					<view class="form-item">
						<text class="label">详细地址</text>
						<textarea class="textarea" v-model="formData.address" placeholder="请输入详细地址" auto-height />
					</view>

					<view class="form-item switch-item">
						<text class="label">设为默认</text>
						<switch class="switch" :checked="formData.status === 1" @change="switchChange" />
					</view>
				</view>

				<button class="save-btn" @click="saveAddress">保存地址</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		getAddressListApi,
		saveAddressApi,
		deleteAddressApi
	} from '../../http/my'

	const addressList = ref([])
	const formData = ref({
		id: null,
		studentId: null,
		studentName: '',
		status: 0, // 0-普通地址 1-默认地址
		receiveName: '',
		receivePhone: '',
		address: ''
	})
	// 控制弹窗显示
	const showPopup = ref(false)
	// 当前是否为编辑模式
	const isEditing = ref(false)
	const sortedAddresses = computed(() => {
		return [...addressList.value].sort((a, b) => b.status - a.status)
	})
	// 选择地址
	const selectAddress = (address) => {
		// 如果是选择模式，返回上一页
		if (uni.getStorageSync('selectAddressMode')) {
			uni.setStorageSync('selectedAddress', address)
			uni.navigateBack()
		}
	}

	// 编辑地址
	const editAddress = (address) => {
		uni.navigateTo({
			url: `/pages/address/edit?id=${address.id}`
		})
	}

	// 新增地址
	const addNewAddress = () => {
		uni.navigateTo({
			url: '/pages/address/edit'
		})
	}

	// 页面显示时刷新数据
	onShow(() => {
		fetchAddressList()
	})

	const updateFormData = (field, value) => {
		formData.value[field] = value;
	};

	// 获取地址列表
	const fetchAddressList = async () => {
		const res = await getAddressListApi(100, 1)
		if (res && res.records) {
			addressList.value = res.records
			console.log('地址列表数据:', res.records)
		} else {
			console.error('获取地址列表失败:', res)
			uni.showToast({
				title: '获取地址列表失败',
				icon: 'none'
			})
		}
	}

	// 显示新增表单
	const showAddForm = () => {
		resetForm()
		isEditing.value = false
		showPopup.value = true
	}

	// 处理编辑
	const handleEdit = (address) => {
		formData.value = {
			...formData.value, // 保留现有值
			id: address.id,
			studentId: address.studentId,
			studentName: address.studentName || '',
			status: address.status || 0,
			receiveName: address.receiveName || '',
			receivePhone: address.receivePhone || '',
			address: address.address || ''
		}
		console.log('formData',formData.value)
		isEditing.value = true
		showPopup.value = true
	}

	// 处理删除
	const handleDelete = async (address) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除该收货地址吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						await deleteAddressApi({
							id: address.id,
							status: address.status || 0
						})
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						fetchAddressList()
					} catch (error) {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
						console.log()
					}
				}
			}
		})
	}
	// 设为默认地址
	const setAsDefault = async (id) => {
		try {
			await saveAddressApi({
				id: id,
				status: 1
			})
			uni.showToast({
				title: '设置成功',
				icon: 'success'
			})
			fetchAddressList()
		} catch (error) {
			uni.showToast({
				title: '设置失败',
				icon: 'none'
			})
		}
	}
	// 保存地址
	const saveAddress = async () => {
		formData.value.status = formData.value.status || 0;
		// 表单验证
		if (!formData.value.receiveName) {
			uni.showToast({
				title: '请输入收货人姓名',
				icon: 'none'
			})
			return
		}

		if (!formData.value.receivePhone || !/^1[3-9]\d{9}$/.test(formData.value.receivePhone)) {
			uni.showToast({
				title: '请输入正确的手机号码',
				icon: 'none'
			})
			return
		}

		if (!formData.value.address) {
			uni.showToast({
				title: '请输入详细地址',
				icon: 'none'
			})
			return
		}

		try {
			// 添加学生信息
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				formData.value.studentId = userInfo.id
				formData.value.studentName = userInfo.username
			}
			closePopup()
			await saveAddressApi(formData.value)
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})

			fetchAddressList()
		} catch (error) {
			closePopup()
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			})
		}
	}

	// 切换默认地址
	const switchChange = (e) => {
		formData.value.status = e.detail.value ? 1 : 0
	}

	// 关闭弹窗
	const closePopup = () => {
		showPopup.value = false
	}

	// 重置表单
	const resetForm = () => {
		formData.value = {
			id: null,
			studentId: null,
			studentName: '',
			status: 0,
			receiveName: '',
			receivePhone: '',
			address: ''
		}
	}
</script>

<style scoped>
	.address-page {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
		/* 给底部按钮留空间 */
	}

	.address-list {
		height: calc(100vh - 160rpx);
	}

	.address-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 25rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.address-header {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.receive-name {
		font-size: 32rpx;
		font-weight: bold;
		margin-right: 15rpx;
	}

	.default-tag {
		background-color: #4facfe;
		color: white;
		font-size: 22rpx;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
	}

	.actions {
		margin-left: auto;
		display: flex;
	}

	.edit-btn,
	.delete-btn {
		font-size: 26rpx;
		color: #666;
		margin-left: 25rpx;
		padding: 8rpx 15rpx;
	}

	.edit-btn {
		color: #4facfe;
	}

	.delete-btn {
		color: #ff6b6b;
	}

	.receive-phone {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
		display: block;
	}

	.address-text {
		font-size: 28rpx;
		line-height: 1.5;
	}

	.address-footer {
		margin-top: 20rpx;
		display: flex;
		justify-content: flex-end;
	}

	.set-default-btn {
		background-color: #fff;
		color: #4facfe;
		border: 1rpx solid #4facfe;
		border-radius: 40rpx;
		padding: 8rpx 30rpx;
		font-size: 26rpx;
		height: auto;
		line-height: 1.5;
	}

	.empty-tip {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.add-btn-container {
		position: fixed;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
	}

	.add-btn {
		background-color: #4facfe;
		color: white;
		border-radius: 50rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
	}

	/* 弹窗遮罩 */
	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: flex-end;
		z-index: 1000;
	}

	.popup-content {
		background-color: #fff;
		border-radius: 30rpx 30rpx 0 0;
		padding: 40rpx;
		width: 100%;
		box-sizing: border-box;
		max-height: 80vh;
		overflow-y: auto;
		z-index: 1001;
	}
	
	.input {
	    z-index: 2000 !important;
	    position: relative;
	  }

	.uni-toast {
		z-index: 2000 !important;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.close-btn {
		font-size: 50rpx;
		color: #999;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.label {
		display: block;
		font-size: 28rpx;
		margin-bottom: 15rpx;
		color: #333;
	}

	.input,
	.textarea {
		border: 1rpx solid #eee;
		border-radius: 10rpx;
		padding: 20rpx;
		font-size: 28rpx;
		background-color: #f9f9f9;
		width: 100%;
		box-sizing: border-box;
	}

	.textarea {
		height: 150rpx;
	}

	.switch {
		transform: scale(0.8);
		transform-origin: left center;
	}

	.save-btn {
		background-color: #4facfe;
		color: white;
		border-radius: 50rpx;
		margin-top: 30rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		width: 100%;
	}
</style>